//
//  KeychainStorage.swift
//  ADKit
//
//  Created by Adoma on 2024/10/17.
//

import SwiftyJSON
import KeychainAccess

/// by ADKit
public class KeychainStorage: DataStorageType {
   
    let storage: Keychain
    
    public init(service: String = Bundle.main.identifier, group: String? = nil) {
        if let accessGroup = group  {
            storage = Keychain(service: service, accessGroup: accessGroup)
        } else {
            storage = Keychain(service: service)
        }
    }
    
    // MARK: JSON
    public func set(json: JSON?, for key: Key)  {
        guard let object = json,
              let data = try? JSONEncoder().encode(object) else {
            remove(key: key)
            return
        }
        try? storage.set(data, key: key)
    }
    
    public func json(for key: Key)  -> JSON? {
        guard let data = try? storage.getData(key) else {
            return nil
        }
        return try? JSONDecoder().decode(JSON.self, from: data)
    }
    
    // MARK: String
    public func set(string: String?, for key: Key)  {
        guard let object = string else {
            remove(key: key)
            return
        }
        try? storage.set(object, key: key)
    }
    
    public func string(for key: Key)  -> String? {
        try? storage.getString(key)
    }
    
    // MARK: Data
    public func set(data: Data?, for key: Key)  {
        guard let object = data else {
            remove(key: key)
            return
        }
        try? storage.set(object, key: key)
    }
    
    public func data(for key: Key)  -> Data? {
        try? storage.getData(key)
    }
    
    public func remove(key: Key)  {
        try? storage.remove(key)
    }
    
    public func clean()  {
        try? storage.removeAll()
    }

}
